package com.rockcent.service.impl;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.BeanToMapUtils;
import com.rockcent.helper.RetrofitHelper;
import com.rockcent.mall.lib.domain.Mall;
import com.rockcent.mall.lib.domain.MallWechatMenuConfig;
import com.rockcent.mall.lib.dto.MallWechatMenuListDTO;
import com.rockcent.mall.lib.helper.MallWechatMenuConfigHelper;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.MallWechatMenuConfigRepository;
import com.rockcent.service.MallWechatApiService;
import com.rockcent.service.MallWechatMenuConfigSrv;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import retrofit2.Response;
import retrofit2.Retrofit;

import java.util.*;

/**
 * Created by zhangjh on 2016/12/5.
 */
@Service
public class MallWechatMenuConfigSrvImpl implements MallWechatMenuConfigSrv {
    private final Logger log = LoggerFactory.getLogger(MallWechatMenuConfigSrvImpl.class);

    private MallWechatApiService mallWechatApiService;
    @Autowired
    private MallRepository mallRepository;

    @Autowired
    private MallWechatMenuConfigRepository mallWechatMenuConfigRepository;

    @Autowired
    private MallWechatMenuConfigHelper mallWechatMenuConfigHelper;

    private static final String WECHAT_URL = "http://127.0.0.1:8881";

    @Override
    public void initWechatMenu(Long mallId) throws Exception {
        Mall mall = mallRepository.findOne(mallId);
//        List<MallWechatMenuConfig> menuList = mallWechatMenuConfigRepository.findByMallIdAndIsDelete(mallId, Whether.NO);
//        log.info("======================>menuList:" + menuList);
//        if (menuList != null && !menuList.isEmpty()) {
//            return;
//        }
        String domain = mall.getCustomerClientDomain();
        log.info("======================>domain{}" + domain);
        if (StringUtils.isBlank(domain)) {
            domain = mall.getMobileHostName();
        }
        log.info("======================>domain{}" + domain);
        if (StringUtils.isNotBlank(domain)) {

            String url = "http://127.0.0.1:8881";
            Retrofit retrofit = RetrofitHelper.SINGLETON.getRetrofit(url);
            mallWechatApiService = retrofit.create(MallWechatApiService.class);
            Response<JsonResult> jsonResultResponse = mallWechatApiService.queryWechatMenuList(domain).execute();
            List<LinkedHashMap> result = (List) jsonResultResponse.body().data;
            List<MallWechatMenuListDTO> menus = new ArrayList<>();
            for (LinkedHashMap map : result) {
                log.info("======================>map{}" + map.toString());
                List arrMaps = (List) map.get("children");
                MallWechatMenuListDTO dto;
                if (null == arrMaps || arrMaps.size() == 0) {
                    log.info("======================>arrMaps==null");
                    dto = (MallWechatMenuListDTO) BeanToMapUtils.SINGLETON.mapToObject(map, MallWechatMenuListDTO.class);
                } else {
                    log.info("======================>arrMaps!=null");
                    dto = new MallWechatMenuListDTO();
                    String name = (String) map.get("name");
                    dto.setName(name);
                    List<MallWechatMenuListDTO> children = new ArrayList<>();
                    for (Object obj : arrMaps) {
                        Map subMap  = (Map)obj;
                        MallWechatMenuListDTO subMenu = (MallWechatMenuListDTO) BeanToMapUtils.SINGLETON.mapToObject(subMap, MallWechatMenuListDTO.class);
                        log.info("======================>subMenu  type {}" + subMenu.getClass().getName());
                        children.add(subMenu);
                    }
                    dto.setChildren(children);
                }
                menus.add(dto);
            }
            if (!menus.isEmpty()) {
                List<MallWechatMenuConfig> menuList = mallWechatMenuConfigRepository.findByMallId(mallId);
                mallWechatMenuConfigRepository.delete(menuList);
                mallWechatMenuConfigHelper.saveList(menus, mallId, new Long(0));
            }


        }


    }

    /**
     * 根据类别分页获取非图文素材列表
     * @param domain 域名
     * @param type 素材类型 素材的类型，图片（image）、视频（video）、语音 （voice）
     * @param offset 偏移位置 int offset 从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
     * @param count 返回数量 int count 取值在1到20之间
     * @throws Exception
     */
    @Override
    public JsonResult materialFileBatchGet(String domain, String type, int offset, int count) throws Exception {
        JsonResult jsonResult = new JsonResult();
        Retrofit retrofit = RetrofitHelper.SINGLETON.getRetrofit(WECHAT_URL);
        mallWechatApiService = retrofit.create(MallWechatApiService.class);
        Response<JsonResult> jsonResultResponse = mallWechatApiService.materialFileBatchGet(domain,type,offset,count).execute();
        if(jsonResultResponse!=null) {
            log.info("======================>materialFileBatchGet:{}", jsonResultResponse.body().data);
            jsonResult.data = jsonResultResponse.body().data;
        }
        return jsonResult;
    }

    /**
     * 根据类别分页获取图文素材列表
     * @param domain 域名
     * @param offset 偏移位置 int offset 从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
     * @param count 返回数量 int count 取值在1到20之间
     * @throws Exception
     */
    @Override
    public JsonResult materialNewsBatchGet(String domain, int offset, int count) throws Exception {
        JsonResult jsonResult = new JsonResult();
        Retrofit retrofit = RetrofitHelper.SINGLETON.getRetrofit(WECHAT_URL);
        mallWechatApiService = retrofit.create(MallWechatApiService.class);
        Response<JsonResult> jsonResultResponse = mallWechatApiService.materialNewsBatchGet(domain,offset,count).execute();
        if(jsonResultResponse!=null) {
            log.info("======================>materialNewsBatchGet:{}", jsonResultResponse.body().data);
            jsonResult.data = jsonResultResponse.body().data;
        }
        return jsonResult;
    }

    /**
     * 获取永久素材
     * @param domain 域名
     * @param type 素材类型
     * @param mediaId 素材ID
     * @return
     * @throws Exception
     */
    @Override
    public JsonResult getMaterialInfo(String domain, String type, String mediaId) throws Exception {
        JsonResult jsonResult = new JsonResult();
        Retrofit retrofit = RetrofitHelper.SINGLETON.getRetrofit(WECHAT_URL);
        mallWechatApiService = retrofit.create(MallWechatApiService.class);
        Response<JsonResult> jsonResultResponse = mallWechatApiService.getMaterialInfo(domain,type,mediaId).execute();
        if(jsonResultResponse!=null) {
            log.info("======================>getMaterialInfo{}", jsonResultResponse.body().data);
            jsonResult.data = jsonResultResponse.body().data;
        }
        return jsonResult;
    }
}
